﻿using System;
using System.Collections;
using System.Drawing;
using System.IO;

namespace ComicReader
{
    public class ComicFile : IDisposable
    {
        private string path;
        private Uncompress uncomp;
        private ArrayList fileList = new ArrayList();
        private FileStream stream;
        private Image actualImage = null;
        private int actualIndex = 0;

        public ComicFile(string path)
        {
            this.path = path;
            this.uncomp = new Uncompress(path);
            string str = this.uncomp.TempPath;
            if ((Directory.GetFiles(str).Length == 0) &&
                (Directory.GetDirectories(str).Length == 1))
                str = Directory.GetDirectories(str)[0];
            foreach (string file in Directory.GetFiles(str))
                fileList.Add(file);
            fileList.Sort();
            loadFile();
        }

        ~ComicFile()
        {
            Dispose(false);
        }

        void IDisposable.Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            Clean();
        }

        public void Clean()
        {
            Uncompress.CleanDirectory(uncomp.TempPath);
        }

        public bool Clean(out string exceptionMessage)
        {
            try
            {
                Uncompress.CleanDirectory(uncomp.TempPath);
                exceptionMessage = null;
                return true;
            }
            catch (Exception e)
            {
                exceptionMessage = e.Message;
                return false;
            }
        }

        private void loadFile()
        {
            stream = new FileStream(fileList[actualIndex] as string, FileMode.Open);
            this.actualImage = Image.FromStream(stream);
            stream.Close();
        }

        public Image Image
        {
            get { return this.actualImage; }
        }

        public Image Next
        {
            get 
            {
                if (++actualIndex < this.fileList.Count - 1)
                    loadFile();
                else
                    actualIndex--;
                return this.actualImage;
            }
        }

        public Image Before
        {
            get 
            {
                if (--actualIndex >= 0)
                    loadFile();
                else
                    actualIndex++;
                return this.actualImage;
            }
        }
    }
}
